package utils.primitif;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.util.Bytes;

public class StringUtils {
	public static String removeBadChar(String s){
		if(s == null)
			return null;
		String pattern = "[^A-Za-z]";
		String strippedString = s.replaceAll(pattern, "").replaceAll("[?!,]", "").trim();
		return strippedString;
	}
	
	public static String removeBadCharButKeepSpace(String s){
		if(s == null)
			return null;
		String pattern = "[^A-Za-z ]";
		String strippedString = s.replaceAll(pattern, "").replaceAll("[?!,]", "").trim();
		return strippedString;
	}
	
	public static boolean startWithWhiteSpace(String s){
		if(s == null)
			return false;
		return s.startsWith(" ");
	}
	
	public static String concatTwoWord(String a, String b){
		StringBuffer toReturn = new StringBuffer();
		toReturn.append(a);
		toReturn.append(" ");
		toReturn.append(b);
		return toReturn.toString();
	}
	
	public static Date getDateFromString(byte[] s){
		if(s == null)
			return null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date d;
		try {
			d = formatter.parse(Bytes.toString(s));
		} catch (ParseException e) {
			System.err.println("Error while parsing date");
			return null;
		}
		return d;
	}

	public static String getStringFromDate(Date d){
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return dateFormat.format(d);
	}
	
	public static String getRealWorldFromStem(HTable tableStem, byte[] row) throws IOException{
		if(row == null)
			return null;
		byte[] stemFamily = Bytes.toBytes("stem");
		String[] thisSplit = Bytes.toString(row).split(" ");
		String realWordS,realWordS2,toReturn;
		if(thisSplit.length > 1){
			byte[] realWord1 = tableStem.get(new Get(Bytes.toBytes(thisSplit[0]))).getValue(stemFamily, Bytes.toBytes(thisSplit[0]));
			byte[] realWord2 = tableStem.get(new Get(Bytes.toBytes(thisSplit[1]))).getValue(stemFamily, Bytes.toBytes(thisSplit[1]));
			realWordS = Bytes.toString(realWord1);
			realWordS2 = Bytes.toString(realWord2);
			if(realWord1 == null){
				realWordS = thisSplit[0];
			}
			if(realWord2 == null){
				realWordS2 = thisSplit[1];
			}
			toReturn = realWordS + " " + realWordS2;
		}else{
			byte[] real = tableStem.get(new Get(row)).getValue(stemFamily,row);
			if(real == null){
				toReturn = (Bytes.toString(row));
			}else{
				toReturn = (Bytes.toString(real));
			}
		}
		return toReturn;
	}
	
	public static void main(String[]a){
		String s = " duhdze uhd uhd";
		s = removeBadCharButKeepSpace(s);

		System.out.println(s);
	}
}
